<script setup>
import { ref } from "vue";

const cartList = ref([
  {
    id: 1,
    name: "商品1",
    price: 100,
    count: 1,
    amount: 200,
  },
  {
    id: 2,
    name: "商品2",
    price: 150,
    count: 1,
    amount: 150,
  },
]);
const count = cartList.value.length;
const checked = ref(false);
const tableRef = ref();
const selected = ref({
  selectNum: 0,
  selectAmount: 0,
  selectList: [],
});

const handleSelecti = (selectedRows) => {
  selected.value.selectNum = selectedRows.length;
  selected.value.selectAmount = selectedRows.reduce((total, row) => total + row.amount, 0);
  selected.value.selectList = selectedRows;
  
  if(selectedRows.length === count) 
  {
    checked.value = true;
  } else {
    checked.value = false;
  }
}

// 处理全选
const handleSelectAll = (val) => {
  checked.value = val;
  if (val) {
    selected.value.selectNum = cartList.value.length;
    selected.value.selectAmount = cartList.value.reduce((total, row) => total + row.amount, 0);
    selected.value.selectList = cartList.value;
    for(let i=0;i<cartList.value.length;i++){
      tableRef.value.toggleRowSelection(cartList.value[i],true);
    }
  } else {
    selected.value.selectNum = 0;
    selected.value.selectAmount = 0;
    selected.value.selectList = [];
    tableRef.value.clearSelection(); // 清除所有选中状态  
  }
}


// 实现增减逻辑
const incrementCount = (id) => {
      const item = cartList.value.find(item => item.id === id);
      if (item) {
        item.count++;
        item.amount = item.count * item.price;
        //如果当前列被选中，则更新选中数量和金额
        if(selected.value.selectList.includes(item)) {
          selected.value.selectNum++;
          selected.value.selectAmount += item.price;
        }
      }
    };

    const decrementCount = (id) => {
      const item = cartList.value.find(item => item.id === id);
      if (item && item.count > 1) {
        item.count--;
        item.amount = item.count * item.price;
        //如果当前列被选中，则更新选中数量和金额
        if(selected.value.selectList.includes(item)) {
          selected.value.selectNum--;
          selected.value.selectAmount -= item.price;
        }
      }
    };

 /**
 * 从购物车中删除指定ID的商品
 * @param {number} itemId - 要删除的商品行ID
 */
 async function deleteFromCart(itemId) {
    const index = cartList.value.findIndex(item => item.id === itemId);

    if (index === -1) {
        // 如果找不到对应的商品，通知用户
        alert('该商品不在购物车中！');
        return;
    }

    // 弹出提示框，询问用户是否确认删除
    const confirmDelete = await ElMessageBox.confirm("确定要删除该商品吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
    });

    if (!confirmDelete) {
        // 用户取消删除操作
        return;
    }

    // 从购物车中移除商品
    cartList.value.splice(index, 1);

    // 更新购物车的显示状态
    updateCartDisplay();
}

/**
 * 更新购物车的显示状态
 */
function updateCartDisplay() {
    // 遍历cart数组，并在页面上为每个商品创建一个列表项
    //重新渲染购物车组件
    console.log('购物车已更新'); // 这只是一个简单的控制台输出，实际应用中可能会有更复杂的操作
}

</script>


<template>
  <div class="container">
    <div class="cart">
      <el-row class="cart-filter-bar">
        <h3>购物车（全部{{ count }}）</h3>
      </el-row>
      <el-row class="cart-list">
        <el-table :data="cartList" 
        ref="tableRef"
        style="width: 100%" @selection-change="handleSelecti" ><el-table-column 
          type="selection" 
          width="55" ></el-table-column>
          <el-table-column
            prop="name"
            label="商品信息"
            width="400"
          ></el-table-column>
          <el-table-column
            prop="price"
            label="单价"
            width="180"
          ></el-table-column>
          <el-table-column
            prop="count"
            label="数量"
            width="180"
          >
          <template #default="{ row }">
              
              <button @click="decrementCount(row.id)">-</button>
              <span style="margin: 0 1rem;">{{ row.count }}</span>
              <button @click="incrementCount(row.id)">+</button>
            </template>
          </el-table-column>
          <el-table-column
            prop="amount"
            label="金额"
            width="180"
          ></el-table-column>
          <el-table-column label="操作">
            <template #default="{ row }">
              <el-button
                type="primary"
                size="small"
                @click="addToFavorites(row.id)"
                >移入收藏</el-button
              >
              <el-button
                type="danger"
                size="small"
                @click="deleteFromCart(row.id)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-row>
      <div class="float-bar">
        <div class="selectAll">
          <el-checkbox v-model="checked" @change="handleSelectAll">全选</el-checkbox>
          <a href=";">删除</a>
        </div>
        <div class="total">
          <span>已选商品</span>
          <span>{{ selected.selectNum }}</span>
          <span>件</span>
          <span>合计（不含运费）：</span>
          <span>￥</span>
          <span>{{ selected.selectAmount }}</span>
          <el-button type="primary" size="small">结算</el-button>
        </div>
      </div>
    </div>
  </div>
</template>


<style scoped lang="scss">
.cart {
  border-radius: 1.5rem;
  border: 1px solid #aaa;
  margin-top: 2rem;
  overflow: hidden;
  background-color: #ffffff;
  .cart-filter-bar {
    height: 6rem;
    line-height: 6rem;
    border-bottom: #aaa solid 1px;
    h3 {
      margin-left: 1.5rem;
      font-size: 1.5rem;
      font-weight: bold;
    }
  }
  .cart-list {
    min-height: 10rem;
    /**设置第一个不显示**/
    .cell:first-child {
        display: none;
      }
  }
  .float-bar {
    height: 6rem;
    line-height: 6rem;
    border-top: #aaa solid 1px;
    background-color: #fafafa;
    .selectAll {
      float: left;
      margin-left: 1.5rem;
      font-size: 1.2rem;
      a {
        margin-left: 1rem;
      }
    }
    .total {
      float: right;
      margin-right: 1.5rem;
      font-size: 1.2rem;

      span {
        margin-left: 1rem;
      }
    }
  }
}
</style>
